﻿#if !HC2020
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.EditorInput;
using Acap = Autodesk.AutoCAD.ApplicationServices.Application;
#else
using GrxCAD.DatabaseServices;
using GrxCAD.EditorInput;
using GrxCAD.Geometry;
using GrxCAD.ApplicationServices;
using GrxCAD.Runtime;
using GrxCAD.Colors;
using GrxCAD.GraphicsInterface;
using Viewport = GrxCAD.DatabaseServices.Viewport;
using Acap = GrxCAD.ApplicationServices.Application;
#endif
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;

namespace JoinBox
{
    public static partial class CadSystem
    {
        //环境变量例子
        //http://www.theswamp.org/index.php?PHPSESSID=ec3e5da499ee486921c266b1b8c22966&topic=20237.msg362446#msg362446
#if AC2006 || AC2007 || AC2008 || AC2009 || AC20081 || AC2011 || AC2012
        [System.Security.SuppressUnmanagedCodeSecurity]
        [DllImport("acad.exe", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Cdecl, EntryPoint = "acedGetEnv")]//名称大小写不能换
        private static extern int AcedGetEnv(string envName, StringBuilder ReturnValue);

        [System.Security.SuppressUnmanagedCodeSecurity]
        [DllImport("acad.exe", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Cdecl, EntryPoint = "acedSetEnv")]
        private static extern int AcedSetEnv(string envName, StringBuilder NewValue);
#elif !HC2020
        [System.Security.SuppressUnmanagedCodeSecurity]
        [DllImport("accore.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Cdecl, EntryPoint = "acedGetEnv")]//名称大小写不能换
        private static extern int AcedGetEnv(string envName, StringBuilder ReturnValue);

        [System.Security.SuppressUnmanagedCodeSecurity]
        [DllImport("accore.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Cdecl, EntryPoint = "acedSetEnv")]
        private static extern int AcedSetEnv(string envName, StringBuilder NewValue);
#endif

#if HC2020
        [System.Security.SuppressUnmanagedCodeSecurity]
        [DllImport("gced.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Cdecl, EntryPoint = "gcedGetEnv")]//名称大小写不能换
        private static extern int AcedGetEnv(string envName, StringBuilder ReturnValue);

        [System.Security.SuppressUnmanagedCodeSecurity]
        [DllImport("gced.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Cdecl, EntryPoint = "gcedSetEnv")]
        private static extern int AcedSetEnv(string envName, StringBuilder NewValue);
#endif

        /// <summary>
        /// 获取系统变量值
        /// </summary>
        /// <param name="name">变量名</param>
        /// <returns>成功获取值,失败null</returns>
        public static string Getvar(string name)
        {
            string re = null;
            try
            {
                object secureload = Acap.GetSystemVariable(name);
                re = secureload.ToString();
            }
            catch
            { }
            if (re == null)
            {
                //环境变量
                re = Getenv(name);
            }
            return re;
        }

        /// <summary>
        /// 设置系统或环境变量
        /// </summary>
        /// <param name="name">变量名</param>
        /// <param name="var">变量值</param>
        /// <returns>成功设置返回值,失败null</returns>
        public static void Setvar(string name, string var)
        {
            if (name == null && var == null)
            {
                return;
            }

            bool setenvOk = true;
            string type = null;
            try
            {
                //改系统变量
                object secureload = Acap.GetSystemVariable(name);
                if (secureload != null)
                {
                    type = secureload.GetType().Name;
                    //如果出现了clayer无法设置,是没有锁文档导致的
                    switch (type)
                    {
                        case "String":
                            Application.SetSystemVariable(name, var.Replace("\"", ""));//去掉引号
                            break;
                        case "Double":
                            Application.SetSystemVariable(name, double.Parse(var));
                            break;
                        case "Int16":
                            Application.SetSystemVariable(name, short.Parse(var));
                            break;
                        case "Int32":
                            Application.SetSystemVariable(name, int.Parse(var));
                            break;
                    }
                    setenvOk = false;
                }
            }
            catch
            {
                var docm = Acap.DocumentManager;
                var doc = docm?.MdiActiveDocument;
                Editor ed = doc?.Editor;

                if (type != null)
                {
                    var str = "\n变量:" + name + "\n出错:" + var + "\n来自:" + type + "\n*******************";
                    if (ed != null)
                    {
                        ed.WriteMessage(str);
                    }
                    else
                    {
                        System.Windows.Forms.MessageBox.Show(str);
                    }
                }
            }
            if (setenvOk)   //改环境变量
            {
                Setenv(name, var);
            }
        }

        /// <summary>
        /// 设置环境变量
        /// </summary>
        /// <param name="name">lisp的名称</param>
        /// <param name="var">要设置的值</param>
        /// <returns></returns>
        public static string Setenv(string name, string var)
        {
            string str;
            try
            {
                var sbRes = new StringBuilder(var);
                AcedSetEnv(name, sbRes);
                str = sbRes.ToString();
            }
            catch (System.Exception e)
            {
                throw e;
            }
            return str;
        }

        /// <summary>
        /// 设置环境变量
        /// </summary>
        /// <param name="name">lisp的名称</param>
        /// <param name="var">要设置的值</param>
        /// <returns></returns>
        public static string Getenv(string name)
        {
            string str;
            try
            {
                var sbRes = new StringBuilder(1024);
                AcedGetEnv(name, sbRes);
                str = sbRes.ToString();
            }
            catch (System.Exception e)
            {
                throw e;
            }
            return str;
        }

        /// <summary>
        /// 返回现有系统变量并设置新系统变量
        /// </summary>
        /// <returns>现有系统变量</returns>
        public static Dictionary<string, string> GetOldVarPairsSetNowVarPairs(Dictionary<string, string> nowPairs)
        {
            //系统变量保存
            var oldPairs = new Dictionary<string, string>();
            if (nowPairs != null)
            {
                //系统变量设置
                foreach (KeyValuePair<string, string> item in nowPairs)
                {
                    oldPairs.Add(item.Key, Getvar(item.Key));
                    Setvar(item.Key, item.Value);
                }
            }
            return oldPairs;
        }
    }
}

